#!/bin/bash
set -e

# 输出目录
CERT_DIR="./certs"
CERT_DIR="./"
mkdir -p "${CERT_DIR}"

# 文件名
CA_KEY="${CERT_DIR}/ca.key.pem"
CA_CERT="${CERT_DIR}/ca.cert.pem"
CA_CRT="${CERT_DIR}/ca.crt"
SERVER_KEY="${CERT_DIR}/server.key.pem"
SERVER_CSR="${CERT_DIR}/server.csr.pem"
SERVER_CERT="${CERT_DIR}/server.cert.pem"
SERVER_EXT="${CERT_DIR}/server.ext.cnf"

# 1️⃣ 生成 CA 私钥
openssl genrsa -out "${CA_KEY}" 4096
echo "生成 CA 私钥: ${CA_KEY}"

# 2️⃣ 生成 CA 自签证书
openssl req -x509 -new -nodes -key "${CA_KEY}" -sha256 -days 3650 \
  -out "${CA_CERT}" \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyOrg/OU=DevOps/CN=MyRootCA"
echo "生成 CA 证书: ${CA_CERT}"

# 3️⃣ 生成服务器私钥
openssl genrsa -out "${SERVER_KEY}" 2048
echo "生成服务器私钥: ${SERVER_KEY}"

# 4️⃣ 生成服务器 CSR（证书签名请求）
openssl req -new -key "${SERVER_KEY}" -out "${SERVER_CSR}" \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyOrg/OU=DevOps/CN=server.local"
echo "生成服务器 CSR: ${SERVER_CSR}"

# 5️⃣ 创建服务器证书扩展配置（支持 SAN）
cat > "${SERVER_EXT}" <<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = server.local
DNS.2 = localhost
IP.1 = 127.0.0.1
EOF

# 6️⃣ 用 CA 签发服务器证书
openssl x509 -req -in "${SERVER_CSR}" -CA "${CA_CERT}" -CAkey "${CA_KEY}" \
  -CAcreateserial -out "${SERVER_CERT}" -days 365 -sha256 -extfile "${SERVER_EXT}"
echo "生成服务器证书: ${SERVER_CERT}"

# 7️⃣ 输出结果
echo "证书生成完成！目录: ${CERT_DIR}"
echo "CA 证书: ${CA_CERT}"
echo "服务器证书: ${SERVER_CERT}"
echo "服务器私钥: ${SERVER_KEY}"
openssl x509 -in ${CA_CERT} -out ${CA_CRT}




# 生成完整证书链
cat server.cert.pem ca.cert.pem > server-chain.pem


#浏览器导入 ca.crt
 